package cn.com.cfae.iras.doc.analyze.components.consistency;

import cn.com.cfae.iras.doc.analyze.components.BaseComponent;
import cn.com.cfae.iras.doc.analyze.components.beans.ComponentResult;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.ChapterModel;
import cn.com.cfae.iras.doc.analyze.parse.model.DocumentModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractBizModel;
import cn.com.cfae.iras.doc.analyze.parse.model.ExtractItem;
import javafx.scene.text.Text;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 佟媛媛 on 18/10/29.
 */

@Component("U1004")
@Scope("prototype")
public class U1004 extends BaseComponent {
    private static Logger logger = LoggerFactory.getLogger(U1004.class);

    /**
     * @desc 检查M-3-1和M-3-2中的上市流通日期是否一致
     * @return
     */
    @Override
    public List<ComponentResult> handlerM() {
        logger.info("开始调用U1004组件，处理M表...............");
        String m31ChapterId="M-3-1";
        String m32ChapterId="M-3-2";
        List<ComponentResult> componentResults = ruleCheck(m31ChapterId,m32ChapterId);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBM() {
        logger.info("开始调用U1004组件，处理BM表...............");
        String bm31ChapterId="BM-3-1";
        String bm32ChapterId="BM-3-2";
        List<ComponentResult> componentResults = ruleCheck(bm31ChapterId,bm32ChapterId);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerDM() {
        logger.info("开始调用U1004组件，处理DM表...............");
        String m31ChapterId="DM-3-1";
        String m32ChapterId="DM-3-2";
        List<ComponentResult> componentResults = ruleCheck(m31ChapterId,m32ChapterId);
        return componentResults;
    }

    @Override
    public List<ComponentResult> handlerBDM() {
        logger.info("开始调用U1004组件，处理BDM表...............");
        String m31ChapterId="BDM-3-1";
        String m32ChapterId="BDM-3-2";
        List<ComponentResult> componentResults = ruleCheck(m31ChapterId,m32ChapterId);
        return componentResults;
    }


    public ComponentResult getComponentResult(String catalogId,String chapterId,
                                               String ruleName,String keyWord,
                                               String promptMsg,Boolean annotationFlag,
                                               String regulationId,int pageNum,
                                               List<ComponentResult.TextPosition> textPositions, String exist){
        ComponentResult componentResult = new ComponentResult();
        componentResult.setCatalogId(catalogId);
        componentResult.setChapterId(chapterId);
        componentResult.setRuleName(ruleName);
        componentResult.setUid(UUID.randomUUID().toString());
        componentResult.setKeyword(keyWord);
        componentResult.setPromptMessage(promptMsg);
        componentResult.setAnnotationFlag(annotationFlag);
        componentResult.setRegulationId(regulationId);
        componentResult.setPageNum(pageNum);
        componentResult.setTextPosition(textPositions);
        componentResult.setExist(exist);
        return  componentResult;

    }


    private List<ComponentResult> ruleCheck(String chapterId1,String chapterId2){
        DocumentModel documentModel = super.getExtractData();

        ChapterModel chapterModel = documentModel.getChapterModel(getCatalogId());

        List<ComponentResult> componentResults = new ArrayList<>();

        String keyword = "检查".concat(chapterId1).concat("发行条款和").concat(chapterId2).concat("发行安排中的上市流通日期是否一致");

        ComponentResult fxtkComponentResult = getComponentResult(getCatalogId(),chapterId1,getRuleTitle(),chapterId1.concat("上市流通日"),"",false,getRegulationId(),3,null,"03");

        ComponentResult fxapComponentResult = getComponentResult(getCatalogId(),chapterId2,getRuleTitle(),chapterId2.concat("上市流通日"),"",false,getRegulationId(),3,null,"03");

        ComponentResult componentResult = getComponentResult(getCatalogId(),chapterId2,getRuleTitle(),keyword,"",false,getRegulationId(),3,null,"03");

        try{
            if(chapterModel!=null){
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

                fxtkComponentResult.setPageNum(chapterModel.getStartPage());
                fxapComponentResult.setPageNum(chapterModel.getStartPage());
                componentResult.setPageNum(chapterModel.getStartPage());

                //发行条款-上市流通日
                KVText fxtkKVTextKey = getKVTextKey(getCatalogId(),"FXTK","SSLTR");

                KVText fxtkKVTextValue = getKVTextValue(getCatalogId(),"FXTK","SSLTR");


                //发行安排-上市流通日
                KVText fxapKVTextKey = getKVTextKey(getCatalogId(),"SSLT","SSLTR");

                KVText fxapKVTextValue = getKVTextValue(getCatalogId(),"SSLT","SSLTR");

                String fxtkDate = null;
                String fxapDate = null;

                Boolean fxtkExistFlag = true;
                Boolean fxapExistFlag = true;

                Boolean fxtkMissFlag = true;
                Boolean fxapMissFlag = true;

                if(fxtkKVTextValue!=null){
                    logger.info("发行条款上市流通日：{}",fxtkKVTextValue.getText());
                    Calendar fxtkCalendar=extractionTime(fxtkKVTextValue.getText());

                    if(fxtkCalendar!=null){
                        logger.info("获取时间：{}",fxtkCalendar.getTime());
                        fxtkDate = simpleDateFormat.format(fxtkCalendar.getTime());
                        logger.info("发行条款上市流通日时间格式化：{}",fxtkDate);
//                        String promptMessage = "已识别，".concat(chapterId1).concat("发行条款中的上市流通日为：").concat(fxtkDate);
                        fxtkComponentResult.setPromptMessage("已识别数据：".concat(fxtkDate));
                    }else{
                        logger.info("发行条款上市流通日为空");
                        String promptMessage ="数据缺失：".concat(fxtkKVTextValue.getText());
                        fxtkComponentResult.setPromptMessage(promptMessage);

                        componentResult.setPromptMessage(promptMessage);

                        fxtkMissFlag = false;
                    }

                    if(fxtkKVTextKey!=null){
                        TextLayout textLayout = fxtkKVTextKey.getTextLayout();
                        List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();
                        ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                        textPosition.setX(textLayout.getLeft());
                        textPosition.setY(textLayout.getTop());
                        textPosition.setContent(textLayout.getText());
                        textPositionList.add(textPosition);
                        fxtkComponentResult.setPageNum(textLayout.getPageNumber());
                        fxtkComponentResult.setTextPosition(textPositionList);
                    }
                }else{
                    fxtkComponentResult.setPromptMessage("未识别");

                    String promptMessage = "未识别".concat(chapterId1).concat("发行条款中的上市流通日，建议人工核对");
                    logger.info("promptMessage：{}",promptMessage);
                    componentResult.setPromptMessage(promptMessage);

                    fxtkExistFlag = false;
                }

                if(fxapKVTextValue!=null){
                    logger.info("发行安排上市流通日：{}",fxapKVTextValue.getText());
                    Calendar fxapCalendar=extractionTime(fxapKVTextValue.getText());

                    if(fxapCalendar!=null){
                        fxapDate = simpleDateFormat.format(fxapCalendar.getTime());
                        logger.info("发行安排上市流通日时间格式化：{}",fxapDate);
//                        String promptMessage = "已识别，".concat(chapterId2).concat("发行安排中的上市流通日为：").concat(fxapDate);
                        fxapComponentResult.setPromptMessage("已识别数据：".concat(fxapDate));
                    }else{
                        logger.info("发行安排上市流通日为空");
                        String promptMessage = "数据缺失：".concat(fxapKVTextValue.getText());
                        fxapComponentResult.setPromptMessage(promptMessage);

                        componentResult.setPromptMessage(promptMessage);

                        fxapMissFlag=false;
                    }

                    if(fxapKVTextKey!=null){
                        TextLayout textLayout = fxapKVTextKey.getTextLayout();
                        List<ComponentResult.TextPosition> textPositionList = new ArrayList<>();
                        ComponentResult.TextPosition textPosition = new ComponentResult().new TextPosition();
                        textPosition.setX(textLayout.getLeft());
                        textPosition.setY(textLayout.getTop());
                        textPosition.setContent(textLayout.getText());
                        textPositionList.add(textPosition);
                        fxapComponentResult.setTextPosition(textPositionList);
                        fxapComponentResult.setPageNum(textLayout.getPageNumber());
                    }
                }else{
                    fxapComponentResult.setPromptMessage("未识别");

                    String promptMessage = "未识别".concat(chapterId2).concat("发行安排中的上市流通日，建议人工核对");
                    logger.info("promptMessage：{}",promptMessage);
                    componentResult.setPromptMessage(promptMessage);

                    fxapExistFlag = false;
                }

                if(!fxtkMissFlag && !fxapMissFlag){
                    String promptMessage = chapterId1.concat("上市流通日数据缺失，").concat(chapterId2).concat("上市流通日").concat("数据缺失，建议人工核对");
                    logger.info("promptMessage：{}",promptMessage);
                    componentResult.setPromptMessage(promptMessage);
                    componentResult.setAnnotationFlag(true);
                    fxtkComponentResult.setAnnotationFlag(true);
                    fxapComponentResult.setAnnotationFlag(true);
                }

                if(!fxtkExistFlag && !fxapExistFlag){
                    String promptMessage = "未识别".concat(chapterId1).concat("发行条款中的上市流通日，未识别").concat(chapterId2).concat("发行安排中的上市流通日").concat("，建议人工核对");
                    logger.info("promptMessage：{}",promptMessage);
                    componentResult.setPromptMessage(promptMessage);
                    componentResult.setAnnotationFlag(true);
                    fxtkComponentResult.setAnnotationFlag(true);
                    fxapComponentResult.setAnnotationFlag(true);
                }

                if(StringUtils.isNotEmpty(fxtkDate) && StringUtils.isNotEmpty(fxapDate)){
                    if(fxtkDate.equals(fxapDate)){
                        logger.info("发行条款上市流通日对比发行安排上市流通日一致");
                        fxtkComponentResult.setPromptMessage("已识别数据：".concat(fxtkDate));
                        fxtkComponentResult.setAnnotationFlag(false);
                        fxtkComponentResult.setExist("01");

                        fxapComponentResult.setPromptMessage("已识别数据：：".concat(fxapDate));
                        fxapComponentResult.setAnnotationFlag(false);
                        fxapComponentResult.setExist("01");

                        componentResult.setPromptMessage("一致");
                        componentResult.setAnnotationFlag(false);
                        componentResult.setExist("01");

                    }else{
                        logger.info("发行安排上市流通日对比发行安排上市流通日不一致");
                        fxtkComponentResult.setPromptMessage(chapterId1.concat("发行条款中的上市流通日为：").concat(fxtkDate).concat("，对比不一致"));
                        fxtkComponentResult.setExist("02");
                        fxtkComponentResult.setAnnotationFlag(true);

                        fxapComponentResult.setPromptMessage(chapterId2.concat("发行安排中的上市流通日为：").concat(fxapDate).concat("，对比不一致"));
                        fxapComponentResult.setExist("02");
                        fxapComponentResult.setAnnotationFlag(true);

                        componentResult.setPromptMessage("不一致");
                        componentResult.setExist("02");
                        componentResult.setAnnotationFlag(true);
                    }
                }else{
                    fxtkComponentResult.setAnnotationFlag(true);
                    fxapComponentResult.setAnnotationFlag(true);
                    componentResult.setAnnotationFlag(true);
                }

                componentResults.add(fxtkComponentResult);
                componentResults.add(fxapComponentResult);
                componentResults.add(componentResult);
                return componentResults;

            }else{
                componentResult.setPromptMessage("未识别".concat(getCatalogId()).concat("数据，建议人工核对"));
                componentResult.setAnnotationFlag(true);
                componentResults.add(componentResult);
                return componentResults;
            }

        } catch (Exception e){
            logger.error(e.getMessage(),e);
        }

        return componentResults;
    }


    public Calendar extractionTime(String text){
        try{
            logger.info("开始处理时间，原值为：{}",text);
            text=text.replaceAll("[\\s|【|】|\\[|\\]|(|)|（|）]{1,}","");
            logger.info("处理时间：{}",text);

            //解析文本，匹配年份
            String yearRegex = "(\\d{1,}年)*";
            Pattern pattern = Pattern.compile(yearRegex);
            Matcher matcher = pattern.matcher(text);
            List<String> yearList = new ArrayList<>();

            while(matcher.find()) {
                if(StringUtils.isNotEmpty(matcher.group())){
                    yearList.add(matcher.group().substring(0,matcher.group().indexOf("年")));
                }
            }
            logger.info("匹配年份：{}",yearList);

            //解析文本，匹配月份
            String monthRegex = "(\\d{1,}月)*";
            List<String> monthList = new ArrayList<>();
            pattern = Pattern.compile(monthRegex);
            matcher = pattern.matcher(text);
            while(matcher.find()) {
                if(StringUtils.isNotEmpty(matcher.group())){
                    monthList.add(matcher.group().substring(0,matcher.group().indexOf("月")));
                }
            }
            logger.info("匹配月份：{}",monthList);

            //解析文本，匹配日期
            String dayRegex = "(\\d{1,}日)*";
            List<String> dayList = new ArrayList<>();
            pattern = Pattern.compile(dayRegex);
            matcher = pattern.matcher(text);
            while(matcher.find()) {
                if(StringUtils.isNotEmpty(matcher.group())){
                    dayList.add(matcher.group().substring(0,matcher.group().indexOf("日")));
                }
            }
            logger.info("匹配日期：{}",monthList);

            if(CollectionUtils.isNotEmpty(yearList) && CollectionUtils.isNotEmpty(monthList) && CollectionUtils.isNotEmpty(dayList)){
                String year=Collections.max(yearList);
                logger.info("年：{}",year);
                String month=Collections.max(monthList);
                logger.info("月：{}",month);
                String day=Collections.max(dayList);
                logger.info("日：{}",day);

                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.YEAR,Integer.parseInt(year));

                if(Integer.valueOf(month)<10){
                    month = month.replace("0","");
                }
                calendar.set(Calendar.MONTH,Integer.valueOf(month)-1);

                if(Integer.valueOf(day)<10){
                    day = day.replace("0","");
                }
                calendar.set(Calendar.DATE,Integer.valueOf(day));

                return calendar;
            }else{
                return null;
            }

        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return null;
        }
    }
}
